-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
57 lines (45 loc) · 1.08 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
void printList(Node* head) {
while (head) {
cout << head->data << " -> ";
head = head->next;
}
cout << "NULL" << endl;
}
void findMiddle(Node* head) {
Node *slow = head, *fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
if (slow) {
cout << "The middle element is: " << slow->data << endl;
}
}
int main() {
int n, value;
cout << "Enter the number of nodes: ";
cin >> n;
Node *head = nullptr, *tail = nullptr;
for (int i = 0; i < n; i++) {
cout << "Enter value for node " << i + 1 << ": ";
cin >> value;
Node* newNode = new Node(value);
if (!head) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
cout << "Original List: ";
printList(head);
findMiddle(head);
return 0;
}